//
//  KRSearchController.m
//  cookBook
//
//  Created by kuroken on 16/1/26.
//  Copyright © 2016年 kuroken. All rights reserved.
//

#import "KRSearchController.h"
#import <PureLayout.h>
#import <SVProgressHUD.h>
#import <MJExtension.h>
#import "KRHttpRecipeTool.h"
#import "KRConst.h"
#import "KRSearchResultController.h"
#import "KRSearchResult.h"
#import "KRSearchGetResult.h"
#import "KRSearchGetListController.h"
#import "KRNoNetCell.h"
#import "KRHomeDataTool.h"

static NSString * const KRKeywordID = @"keyword";

@interface KRSearchController () <UISearchBarDelegate, UITableViewDataSource, UITableViewDelegate, KRSearchResultControllerDelegate, KRSearchGetListControllerDelegate>
//@property (nonatomic, weak) UIView *navBarView;
@property (nonatomic, weak) UISearchBar *searchBar;
//@property (nonatomic, weak) UIButton *cancelBtn;
/** UITableView */
@property (nonatomic, weak) UITableView *tableView;
/** 搜索结果控制器 */
@property (nonatomic, strong) KRSearchResultController *searchResultVc;
/** KRSearchResult 模型 */
@property (nonatomic, strong) KRSearchResult *result;
/** 展示结果列表控制器 */
@property (nonatomic, strong) KRSearchGetListController *searchGetListVc;

/** tableView底部约束 */
@property (nonatomic, strong) NSLayoutConstraint *tableViewBottomConstraint;

/** 当前请求 */
@property (nonatomic, weak) NSURLSessionDataTask *currentDataTask;

/** 搜索历史 */
@property (nonatomic, strong) NSArray<NSString *> *keywordArray;

@end

@implementation KRSearchController

- (KRSearchGetListController *)searchGetListVc
{
    if (!_searchGetListVc) {
        self.searchGetListVc = [[KRSearchGetListController alloc] init];
        self.searchGetListVc.delegate = self;
        [self addChildViewController:self.searchGetListVc];
        [self.view addSubview:self.searchGetListVc.tableView];
        [self.searchGetListVc.tableView autoPinEdgeToSuperviewEdge:ALEdgeTop withInset:64];
        [self.searchGetListVc.tableView autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsZero excludingEdge:ALEdgeTop];
    }
    return _searchGetListVc;
}


- (KRSearchResultController *)searchResultVc
{
    if (!_searchResultVc) {
        self.searchResultVc = [[KRSearchResultController alloc] init];
        self.searchResultVc.delegate = self;
        [self addChildViewController:self.searchResultVc];
        [self.view addSubview:self.searchResultVc.tableView];
        [self.searchResultVc.tableView autoPinEdgeToSuperviewEdge:ALEdgeTop withInset:64];
        [self.searchResultVc.tableView autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsZero excludingEdge:ALEdgeTop];
    }
    return _searchResultVc;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:KRKeywordID];
    
    [self.view setBackgroundColor:[UIColor whiteColor]];
    
    // 隐藏返回按钮
    self.navigationItem.hidesBackButton = YES;
    
//    self.automaticallyAdjustsScrollViewInsets = YES;
    
    // 创建UITableView
    UITableView *tableView = [[UITableView alloc] init];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.tableFooterView = [[UIView alloc] init];
    self.tableView = tableView;
    [self.view addSubview:tableView];
    [tableView autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsZero excludingEdge:ALEdgeBottom];
    [NSLayoutConstraint autoSetPriority:UILayoutPriorityDefaultLow forConstraints:^{
        self.tableViewBottomConstraint = [tableView autoPinEdgeToSuperviewEdge:ALEdgeBottom];
    }];
    
    UISearchBar *searchBar = [[UISearchBar alloc] init];
    searchBar.placeholder = @"搜索菜谱、专辑";
    [searchBar setImage:[UIImage imageNamed:@"homeSearch"] forSearchBarIcon:UISearchBarIconBookmark state:UIControlStateNormal];
    searchBar.delegate = self;
    self.searchBar = searchBar;
    self.navigationItem.titleView = searchBar;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@" 取消 " style:UIBarButtonItemStylePlain target:self action:@selector(cancelBtnClick)];

}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];

    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self.searchBar becomeFirstResponder];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.searchBar resignFirstResponder];
    [self.currentDataTask cancel];
    self.currentDataTask = nil;
}

- (void)dealloc
{
    if (_searchGetListVc) {
        [self.searchGetListVc.view removeFromSuperview];
        [self.searchGetListVc removeFromParentViewController];
        self.searchGetListVc = nil;
    }
    if (_searchResultVc) {
        [self.searchResultVc.view removeFromSuperview];
        [self.searchResultVc removeFromParentViewController];
        self.searchResultVc = nil;
    }
    NSLog(@"%s", __func__);
}

/**
 *  解决键盘遮挡tableView问题
 */
- (void)keyboardWillChangeFrame:(NSNotification *)notification
{
    CGFloat keyBoardHeight = [notification.userInfo[@"UIKeyboardFrameEndUserInfoKey"] CGRectValue].size.height;
//    KRLog(@"键盘高度 : %f", keyBoardHeight);
    [self.tableViewBottomConstraint autoRemove];
    [NSLayoutConstraint autoSetPriority:UILayoutPriorityDefaultHigh forConstraints:^{
        self.tableViewBottomConstraint = [self.tableView autoPinEdgeToSuperviewEdge:ALEdgeBottom withInset:keyBoardHeight];
    }];
    
}

/**
 *  点击键盘search按钮时调用
 */
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    // 显示searchGetListVc.tableview
    self.searchGetListVc.tableView.hidden = NO;
    // 清除旧数据
    if (self.searchGetListVc.keyword) {
        self.searchGetListVc.keyword = nil;
    }
   
    NSString *keyword = searchBar.text;
    // 设置searchGetListVc的搜索关键字
    self.searchGetListVc.keyword = keyword;
    // 退出键盘
    [self.searchBar resignFirstResponder];
}

/**
 *  搜索框文字改变时调用
 */
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    if (_searchGetListVc.keyword) { // 搜索框文字改变时，清空searchGetListVc.tableView
        [SVProgressHUD dismiss];
        self.searchGetListVc.tableView.hidden = YES;
        self.searchGetListVc.keyword = nil;
    }
    if (searchText.length) {
        self.searchResultVc.view.hidden = NO;
        [self loadSearchDataWithKeyword:searchText];
    } else {
        [self.tableView reloadData];
        self.searchResultVc.view.hidden = YES;
        [self loadSearchDataWithKeyword:nil];
    }
}

/**
 *  加载搜索请求
 */
- (void)loadSearchDataWithKeyword:(NSString *)keyword
{
    if (!keyword) { // 搜索框清空时，刷新tableView
        self.searchResultVc.result = nil;
        [SVProgressHUD dismiss];
        return;
    }
    
    if (_currentDataTask) {
        [self.currentDataTask cancel];
    }
    self.currentDataTask = [KRHttpRecipeTool getParams:^(NSString *__autoreleasing *method, NSMutableDictionary *requestParams) {
        *method = KRSearchGetSuggestion;
        requestParams[@"keyword"] = keyword;
    } success:^(NSURLSessionDataTask *task, id json) {
        if (self.currentDataTask != task) return;

        // 网络延迟情况下，返回的数据与当前搜索框的内容不匹配，则return。
        if (![self.searchBar.text isEqualToString:keyword]) return ;
        
        self.result = [KRSearchResult mj_objectWithKeyValues:json[@"result"]];
        self.searchResultVc.result = self.result;
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        if (self.currentDataTask != task) return;
        if (![self.searchBar.text isEqualToString:keyword]) return ;
        KRLog(@"%@, %@", self, error);
    }];
    
}



#pragma mark - KRSearchGetListControllerDelegate
- (void)searchGetListControllerDidStartScroll
{
    if (_searchGetListVc && !_searchGetListVc.view.isHidden) {
        // 退出键盘
        [self.searchBar resignFirstResponder];
    }
}

- (void)cancelBtnClick
{
//    [self.navBarView removeFromSuperview];
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - KRSearchResultControllerDelegate
- (void)searchResultControllerDidSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 显示searchGetListVc.tableview
    self.searchGetListVc.tableView.hidden = NO;
    if (_searchResultVc) {
        self.searchResultVc.tableView.hidden = YES;
    }
    
    NSString *keyword = self.result.list[indexPath.row];
    // 设置searchGetListVc的搜索关键字
    self.searchGetListVc.keyword = keyword;
    // 设置搜索框文字
    [self.searchBar setText:keyword];
    // 退出键盘
    [self.searchBar resignFirstResponder];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // 获取历史记录
    self.keywordArray = [KRHomeDataTool searchData];

    return self.keywordArray.count ? 1 : 0;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.keywordArray.count + 1;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:KRKeywordID];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:KRKeywordID];
    }
    if (indexPath.row == 0) {
        [cell.textLabel setText:[NSString stringWithFormat:@"清空历史记录"]];
        [cell.textLabel setTextColor:[UIColor lightGrayColor]];
    } else {
        [cell.textLabel setText:[NSString stringWithFormat:@"%@", self.keywordArray[indexPath.row - 1]]];
        [cell.textLabel setTextColor:[UIColor blackColor]];
    }
    [cell.imageView setImage:[UIImage imageNamed:@"ico_cell_history"]];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) { // 清空历史记录
        [KRHomeDataTool deleteSearchData];
        [self.tableView reloadData];
    } else {
        // 设置searchGetListVc的搜索关键字
        NSString *keyword = self.keywordArray[indexPath.row - 1];
        self.searchBar.text = keyword;
        self.searchGetListVc.keyword = keyword;
        
        // 显示searchGetListVc.tableview
        self.searchGetListVc.tableView.hidden = NO;
        
        // 退出键盘
        [self.searchBar resignFirstResponder];
        
    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

@end
